package com.flowerplus.store.common.data.utils.ui;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;

/**
 * Created by z on.
 * Des:fragment管理类
 * Date: 2017/3/7
 */

public class FragmentManagerUtil {

    private Fragment[] mFragments;
    private FragmentManager mFragmentManager;
    private int mResoucesId;
    private int mCurrentIndex;

    public FragmentManagerUtil(int resoucesId, FragmentManager fragmentManagers, Fragment[] fragments) {

        if (fragments == null || fragments.length == 0) {
            throw new NullPointerException("fragments is null or fragments length==0");
        }
        if (fragmentManagers == null) {
            throw new NullPointerException("FragmentManager is null");
        }
        mResoucesId = resoucesId;
        mFragments = fragments;
        mFragmentManager = fragmentManagers;
        initFragment();
    }

    private void initFragment() {
        FragmentTransaction ft = mFragmentManager.beginTransaction();
        for (int i = 0; i < mFragments.length; i++) {
            ft.add(mResoucesId, mFragments[i], mFragments[i].getClass().getSimpleName()).hide(mFragments[i]);
        }
        ft.show(mFragments[0]);
        ft.commitAllowingStateLoss();
    }

    public void showFragment(int index) {
        if (index == mFragments.length || index > mFragments.length || index < 0) {
            throw new IndexOutOfBoundsException("index==" + mFragments.length + " fragments  length is " + mFragments.length);
        }
        FragmentTransaction ft = mFragmentManager.beginTransaction();
        for (int i = 0; i < mFragments.length; i++) {
            if (i == index) {
                ft.show(mFragments[i]).commitAllowingStateLoss();
            } else {
                hideFragment(mFragments[i]);
            }
        }
        mCurrentIndex = index;
    }

    public void hideFragment(Fragment fragment) {
        mFragmentManager.beginTransaction().hide(fragment).commitAllowingStateLoss();
    }

    public void hideFragment(int position) {
        mFragmentManager.beginTransaction().hide(mFragments[position]).commitAllowingStateLoss();
    }

    /**
     * 隐藏所有的fragment
     */
    public void hideAllFragment() {
        FragmentTransaction ft = mFragmentManager.beginTransaction();
        for (Fragment fragment : mFragments) {
            ft.hide(fragment).commitAllowingStateLoss();
        }
    }

    public int getCurrentIndex() {
        return mCurrentIndex;
    }

    public Fragment getCurrentFragment() {
        return mFragments[mCurrentIndex];
    }
}
